import React from "react";
import {
  Form,
  Input,
  Button,
  DatePicker,
  TimePicker,
  Transfer,
  message,
  Tag,
  Radio,
  Tabs,
  List,
  Select,
} from "antd";
import axios from "axios";
import qs from "qs";
import "../mock/meetingdata";
import "../mock/group";
import "../mock/groupMembers";
import "../mock/fechLeader";
import OrgTree from "./OrgTree";
import moment from "moment";
const { TabPane } = Tabs;
const { Option } = Select;

export default class AddMeeting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      addVisible: false,
      // mockData: ['李亮','张明','李飞','王培'],//职工列表
      enableMockData: [], //职工列表
      enableTargetKeys: [],
      isEnable: "",
      rules: [
        {
          required: true,
          message: "此项不可为空",
        },
      ],
      treeData: [],
      changeDataSource: props.changeDataSource,
      personnelGroup: [],
      startTime: "00:00",
      endTime: "00:00",
      leaders: [],
      buttomText: "保存",
    };
    this.setTreeData = this.setTreeData.bind(this);
    this.treeOnSelect = this.treeOnSelect.bind(this);
  }

  formRef = React.createRef();
  /**弹出对话框 */
  showAddModal = () => {
    this.setState({
      addVisible: true,
    });
  };

  /**添加参会人 */
  handleEnableChange = (enableTargetKeys) => {
    this.setState({ enableTargetKeys });
  };

  // 获取职工树
  getTreedata = () => {
    const treeData = this.getTree(this.props.staffList);
    this.setState({ treeData });
  };
  getTree = (value) => {
    if (value.length) {
      return value.map((item, i) => {
        return {
          key: item.depId,
          title: item.depName,
          value: item.data,
          children: this.getTree(item.children),
        };
      });
    }
  };
  enableChange = (e) => {
    // console.log(e.target.value);
    this.setState({
      isEnable: e.target.value === 1 ? "500px" : "0px",
    });
  };

  componentDidMount() {
    this.getPersonnelGroup();
    // 调用父组件方法把当前实例传给父组件
    if (this.props.onRef) {
      this.props.onRef("AddMeeting", this);
    }

    /**获取领导组数据 */
    this.getLeadersData();

    /**url中含有id字段时，修改该id的会议*/
    // console.log(this.props.location);
    if (this.props.location) {
      let Params = this.props.location.search;
      if (Params.indexOf("layerId") > 0) {
        this.setState({ buttomText: "添加" });
      }
    }
  }

  getLeadersData = () => {
    /**获取领导组数据 */
    axios
      .get("../weekmeeting/fechLeader.rst")
      .then((res) => {
        let response = res.data;
        if (response.resultCode === 0) {
          this.setState({
            leaders: response.result.data,
          });
        } else {
          // alert('获取职工数据失败')
          message.error("领导组请求失败");
        }
      })
      .catch((error) => {
        // alert('获取职工数据失败')
        message.error("领导组请求失败");
      });
  };

  /**机构数据 */
  setTreeData = (treeData) => {
    setTimeout(() => {
      this.setState({ treeData });
    }, 0);
  };

  /*点击部门列表,展示部门人员 */
  treeOnSelect = (value) => {
    // console.log(value);
    // this.getMock(isHost, value);
    axios
      .get("../weekmeeting/searchUsers.rst?orgId=" + value[0])
      .then((res) => {
        let response = res.data;
        // console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */
          this.setState({
            enableMockData: res.map((person) => {
              return {
                key: person.EMPID + "_" + person.EMPNAME,
                title: person.EMPID + "_" + person.EMPNAME,
              };
            }),
          });
        } else {
          // message.error("人员数据请求失败");
        }
      })
      .catch((error) => {
        message.error("人员数据请求失败");
      });
  };

  /**关闭Tag */
  handleEnableTagClose = (removedTag) => {
    const enableTargetKeys = this.state.enableTargetKeys.filter(
      (enableTargetKeys) => enableTargetKeys !== removedTag
    );
    console.log(enableTargetKeys);
    this.setState({ enableTargetKeys });
  };

  /*遍历插入Tag */
  enableForMap = (tag) => {
    console.log(tag);
    return (
      <span key={tag} style={{ display: "inline-block", marginBottom: 16 }}>
        <Tag
          closable
          color="blue"
          onClose={(e) => {
            e.preventDefault();
            this.handleEnableTagClose(tag);
          }}
        >
          {tag}
        </Tag>
      </span>
    );
  };

  /*获取人员组数据 */
  getPersonnelGroup = () => {
    axios
      .get("../weekmeeting/group.rst")
      .then((res) => {
        let response = res.data;
        // console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */
          this.setState({
            personnelGroup: res.map((group) => {
              return {
                label: group.groupName,
                value: group.groupName,
                groupId: group.groupId,
              };
            }),
          });
        } else {
          // message.error("人员组请求失败");
        }
      })
      .catch((error) => {
        message.error("人员组请求失败");
      });
  };

  /**选择人员组 */
  personnelGroupOnClick = (item) => {
    // console.log(item.member);
    axios
      .get("../weekmeeting/groupMembers.rst?groupId=" + item.groupId)
      .then((res) => {
        let response = res.data;
        // console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */
          this.setState({
            enableMockData: res.map((person) => {
              return {
                key: person.EMPID + "_" + person.EMPNAME,
                title: person.EMPID + "_" + person.EMPNAME,
              };
            }),
          });
        } else {
          // message.error("人员数据请求失败");
        }
      })
      .catch((error) => {
        message.error("人员数据请求失败");
      });
  };

  /**选择会议时段 */
  timeQuantumOnChange = (e) => {
    // console.log("radio checked", e.target.value);

    // eslint-disable-next-line default-case
    switch (e.target.value) {
      case 2:
        this.setState({
          startTime: "08:30",
          endTime: "17:30",
        });
        break;

      case 3:
        this.setState({
          startTime: "08:30",
          endTime: "11:30",
        });
        break;
      case 4:
        this.setState({
          startTime: "13:30",
          endTime: "17:00",
        });
        break;
      case 5:
        this.setState({
          startTime: "18:00",
          endTime: "20:30",
        });
        break;
    }
  };

  handleCancel = () => {
    /**清空修改表单状态 */
    this.formRef.current.resetFields();
    this.setState({
      hostTargetKeys: [],
      enableTargetKeys: [],
      loading: false,
      addVisible: false,
    });
  };

  onFinish = (values) => {
    // 进入提交
    let isEnabl = 0;
    this.setState({ loading: true });
    let enableData = "";
    if (this.state.isEnable !== "0px") {
      //分享
      console.log(this.state.enableTargetKeys);
      enableData = this.state.enableTargetKeys.join();
      isEnabl = 1;
    }
    console.log(values.leaders);
    /**添加活动数据 */
    axios
      .post(
        "../weekmeeting/addMeetingSchoool.rst ",
        qs.stringify({
          meetingDate: values.date.format("YYYY-MM-DD"),
          meetingTime: this.state.startTime,
          meetingEndTime: this.state.endTime,
          locale: values.address,
          theme: values.content,
          person: enableData,
          enable: isEnabl,
          remark: values.remark,
          leaders: values.leaders.join(),
          responsibleDepartment: values.responsibleDepartment,
        })
      )
      .then((res) => {
        let response = res.data;
        console.log(response);
        if (response.resultCode === 0) {
          /**清空并关闭添加表单 */
          this.formRef.current.resetFields();
          this.setState({
            hostTargetKeys: [],
            enableTargetKeys: [],
            loading: false,
            addVisible: false,
          });
          /**重新渲染活动列表 */
          message.success("提交成功");
          this.props.getDataSource();
          if (window.parent) {
            //本页面作为iframe打开时，添加完成后关闭窗口
            var iframe = document.createElement("iframe");
            iframe.setAttribute("style", "position:absolute;left:-9999999px;top:-999999px;");
            iframe.setAttribute("src", "https://portal.zjbti.net.cn/_web/customized/scheduleCenter/closeWindow.html");
            document.body.appendChild(iframe)
          }
        } else {
          this.setState({ loading: false, addVisible: false });
          // message.error("提交失败");
        }
      })
      .catch((error) => {
        this.setState({ loading: false, addVisible: false });
        // message.error("提交失败");
      });
  };
  render() {
    const {
      loading,
      startTime,
      endTime,
      rules,
      enableTargetKeys,
      treeData,
      enableMockData,
      personnelGroup,
      leaders,
      buttomText,
    } = this.state;
    /**领导组数据 */
    const leadersOption = leaders.map((item) => {
      return <Option key={item.id + "_" + item.name}>{item.name}</Option>;
    });

    /**添加活动数据 */

    // const {
    //   rules,
    //   enableTargetKeys,
    //   treeData,
    //   enableMockData,
    //   personnelGroup,
    // } = this.state;
    const enableTag = enableTargetKeys.map(this.enableForMap);

    return (
      <>
        {/* <Button type="primary" onClick={this.showAddModal}>
          <PlusCircleOutlined />
          增加
        </Button> */}

        <Form
          name="add-meeting"
          onFinish={this.onFinish} /**表单提交事件 */
          className="search-meet"
          ref={this.formRef}
        >
          <Form.Item name="date" label="日期" rules={rules}>
            <DatePicker format="YYYY-MM-DD" />
          </Form.Item>

          <Form.Item name="content" label="事件内容" rules={rules}>
            <Input />
          </Form.Item>
          <Form.Item name="address" label="地点" rules={rules}>
            <Input />
          </Form.Item>
          <Form.Item
            name="startTime"
            label="开始时间"
            rules={rules}
            initialValue={moment(startTime, "HH:mm")}
            // key={startTime}
          >
            <TimePicker
              key={startTime}
              defaultValue={moment(startTime, "HH:mm")}
              format="HH:mm"
              value={moment(startTime, "HH:mm")}
              onChange={(time, timeString) =>
                this.setState({ startTime: timeString })
              }
            />
            <input hidden={true} value={startTime} />
          </Form.Item>
          <Form.Item
            name="endTime"
            label="结束时间"
            rules={rules}
            initialValue={moment(endTime, "HH:mm")}
            // key={startTime}
          >
            <TimePicker
              key={endTime}
              defaultValue={moment(endTime, "HH:mm")}
              format="HH:mm"
              value={moment(endTime, "HH:mm")}
              onChange={(time, timeString) =>
                this.setState({ endTime: timeString })
              }
            />
            <input hidden={true} value={endTime} />
          </Form.Item>
          <Form.Item name="timeQuantum" label="">
            <Radio.Group onChange={this.timeQuantumOnChange} value={1}>
              {/* <Radio value={1}>无</Radio> */}
              <Radio value={2}>全天</Radio>
              <Radio value={3}>上午</Radio>
              <Radio value={4}>下午</Radio>
              <Radio value={5}>晚上</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="responsibleDepartment" label="责任部门">
            <Input />
          </Form.Item>
          {/* <Form.Item name="leaders" label="出席领导" rules={rules}>
            <Input />
          </Form.Item> */}
          <Form.Item name="leaders" label="出席领导" rules={rules}>
            <Select
              mode="multiple"
              allowClear
              style={{ width: "100%" }}
              placeholder="请选择"
              // defaultValue={["a10", "c12"]}
              // onChange={handleChange}
              // options={this.props.leaders}
            >
              {leadersOption}
            </Select>
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input />
          </Form.Item>
          <Form.Item name="enable" label="是否分享">
            <Radio.Group
              name="enable"
              onChange={this.enableChange}
              defaultValue={1}
            >
              <Radio value={1}>分享</Radio>
              <Radio value={0}>不分享</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="enable"
            label="分享范围"
            // rules={rules}
            className="enableSelect"
            style={{ maxHeight: this.state.isEnable }}
          >
            {enableTag}
            <Tabs
              defaultActiveKey="1"
              type="card"
              size="small"
              className="OrgTreeTab"
            >
              <TabPane tab="人员机构" key="1">
                <OrgTree
                  treeData={treeData}
                  setTreeData={this.setTreeData}
                  treeOnSelect={this.treeOnSelect}
                  isHost={false}
                />
              </TabPane>
              <TabPane tab="人员组" key="2">
                <List
                  className="personnelGroup"
                  size="small"
                  itemLayout="horizontal"
                  dataSource={personnelGroup}
                  renderItem={(item) => (
                    <List.Item>
                      <List.Item.Meta
                        title={item.value}
                        member={item.member}
                        onClick={() => this.personnelGroupOnClick(item)}
                      />
                    </List.Item>
                  )}
                />
              </TabPane>
            </Tabs>

            <Transfer
              dataSource={enableMockData}
              targetKeys={enableTargetKeys}
              // selectedKeys={enableTargetKeys}
              showSearch
              listStyle={{
                width: 250,
                height: 200,
              }}
              operations={["添加", "移出"]}
              onChange={this.handleEnableChange}
              render={(item) => item.title}
            />
          </Form.Item>
          <Button type="primary" htmlType="submit" loading={loading}>
            {buttomText}
          </Button>
        </Form>
      </>
    );
  }
}
